myApp.template = {
    render: function (selector, data) {
        let tpl = complie($$(selector).html());
        return render(tpl, data);
    }
};

let complie = function (str) {
    let tpl = str.replace(/\n/g, '\\n') // 将换行符?换
        .replace(/<%=([\s\S]+?)%>/g, function (match, code) {
            return "' + escape(" + code + ") + '";
            // return "' + " + code + " + '";//需要转义
        })
        .replace(/<%=([\s\S]+?)%>/g, function (match, code) {
            return "' + " + code + "+ '";
        })
        .replace(/<%([\s\S]+?)%>/g, function (match, code) {
            return "';\n" + code + "\ntpl += '";
        })
        .replace(/\'\n/g, '\'')
        .replace(/\n\'/gm, '\'');
    tpl = "tpl = '" + tpl + "';";
    // 转换空行
    tpl = tpl.replace(/''/g, '\'\\n\'');
    tpl = 'var tpl = "";\nwith (obj || {}) {\n' + tpl + '\n}\nreturn tpl;';
    return new Function('obj', tpl);
};

let escape = function (html) {
    return String(html)
        .replace(/&(?!\w+;)/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;'); // IE?不支持&apos;?单引??转义
};

let render = function (complied, data) {
    return complied(data);
};

